<script lang="ts" setup>
import { onLoad, onShow } from "@dcloudio/uni-app";
import { ref } from "vue";

import { useAppStore } from "@/stores/appStore";  // 导入应用状态管理
import { apiGetRemind, apiGetUserRecord, apiGetUser, apiChangeUser } from "../../apis/apis.js"
const selectedImage = ref("https://farmmanger-1338284214.cos.ap-shanghai.myqcloud.com/farmer.png"); // 默认头像图片
const remindList = ref<{ block: string; time: string; content: string }[]>([]);
const remindCount = ref(0);
const recordCount = ref(0);
const userInfo = ref();
const appStore = useAppStore();  // 获取应用状态管理实例
const uid = appStore.uid;  // 获取用户ID
//将uid转换为字符串类型且为8位
const uidString = uid.toString().padStart(8, '0');
const getRecord = async () => {
  try {
    const res = await apiGetUserRecord({}, uid)
    console.log(res.data);
    recordCount.value = res.data.rows.length;

  } catch (error) {
    console.error(error);
  }
}
// const changeUser = async (query:Object) => {
//   try {
//     const res = await apiChangeUser(query,uid)
//     console.log(res.data);
//   } catch (error) {
//     console.error(error);
//   }
// }
const getUser = async () => {
  try {
    const res = await apiGetUser({ uid: uid })
    userInfo.value = res.data.rows[0];
    console.log(userInfo.value);

    selectedImage.value = res.data.rows[0].avatar ? res.data.rows[0].avatar : "https://farmmanger-1338284214.cos.ap-shanghai.myqcloud.com/farmer.png"
    console.log(res.data);
  } catch (error) {
    console.error(error);
  }
}
const getRemind = async () => {
  try {
    const res = await apiGetRemind({ uid: appStore.uid, deleteDelay: 1 })
    console.log(res.data);
    if (res.data.rows.length === 0) {
      remindList.value = [{ block: "", time: "", content: "暂无提醒" }]
    }
    else {
      //将rows中内容转换为: 明天上午8点区块A1:水稻施肥提醒... 的格式,使用map方法
      res.data.rows = res.data.rows.map((item: any) => {
        const date = new Date(item.time);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        const period = Number(hours) >= 12 ? '下午' : '上午';
        return { block: item.block, time: `${month}-${day}${period}${hours}:${minutes}`, content: item.content }
      })
      remindList.value = res.data.rows;
      remindCount.value = res.data.rows.length;
      console.log(remindList.value);

    }

  }
  catch (error) {
    console.error(error);
  }
}


const getMoreRemind = () => {
  //跳转页面
  uni.navigateTo({ url: "/pages/RemindList/index" })
};
const getMoreRecord = () => {
  //跳转页面
  uni.navigateTo({ url: "/pages/Records/recordList" })
};
const changeMail = () => {
  //弹窗出现输入框，输入新的邮箱地址
  uni.showModal({
    title: '修改邮箱',
    content: '',
    editable: true,
    placeholderText: '请输入新的邮箱地址',
    success: (res) => {
      if (res.confirm) {
        //发送验证请求
       
        //验证码弹窗
        uni.showModal({
          title: '验证码',
          content: '',
          editable: true,
          success: (success) => {
            if (success.confirm && success.content === '123456') {
              const newMail = res.content;
            // 这里可以进行邮箱的验证和更新操作
             console.log('新的邮箱地址:', newMail);
               apiChangeUser({ email: newMail }, uid)
              uni.showToast({
                title: '修改成功',
                icon: 'success',
                mask: true
              })

            }else {
              uni.showToast({
                title: '验证码错误',
                icon: 'none',
              })
            }
          },
        })
      
      }
    }
  });
}
const changePhone = () => {
  //弹窗出现输入框，输入新的手机号
  uni.showModal({
    title: '修改手机号',
    content: '',
    editable: true,
    placeholderText: '请输入新的手机号',
    success: (res) => {
      if (res.confirm) {
        //发送验证请求
       
        //验证码弹窗
        uni.showModal({
          title: '验证码',
          content: '',
          editable: true,
          success: (success) => {
            if (success.confirm && success.content === '123456') {
              const newPhone = res.content;
              // 这里可以进行手机号的验证和更新操作
              console.log('新的手机号:', newPhone);
              apiChangeUser({ phone: newPhone }, uid)
              uni.showToast({
                title: '修改成功',
                icon: 'success',
                mask: true
              })

            }else {
              uni.showToast({
                title: '验证码错误',
                icon: 'none',
              })
            }
          },
        })


      }
    }
  });
}
const changeName = () => {
  //弹窗出现输入框，输入新的手机号
  uni.showModal({
    title: '修改用户名',
    content: '',
    editable: true,
    placeholderText: '请输入新的用户名',
    success: (res) => {
      if (res.confirm) {
        const newName = res.content;
        // 这里可以进行手机号的验证和更新操作
        console.log('新的用户名:', newName);
        apiChangeUser({ username: newName }, uid)
        uni.showToast({
          title: '修改成功',
          icon:'success',
          mask: true 
        })
      }
    }
  });
}
const changeAvatar = () => {
  // 弹窗出现选择器
  uni.showActionSheet({
    itemList: ['拍照', '从相册中选择'],
    success: (actionRes) => {
      let sourceType = [];
      if (actionRes.tapIndex === 0) {
        sourceType = ['camera']; // 拍照
      } else if (actionRes.tapIndex === 1) {
        sourceType = ['album']; // 相册
      } else {
        return;
      }

      // 选择图片
      uni.chooseImage({
        count: 1, // 这里只允许选择一张头像
        sizeType: ['original', 'compressed'],
        sourceType: sourceType,
        success: (chooseRes) => {
          const tempFilePath = chooseRes.tempFilePaths[0];

          // 预览选中的图片
          uni.previewImage({
            urls: [tempFilePath],
            current: tempFilePath,
            success: () => {
              // 预览完成后弹窗询问用户是否上传
              uni.showModal({
                title: '确认上传？',
                content: '确认将此图片作为你的头像？',
                success: async (modalRes) => {
                  if (modalRes.confirm) {
                    // 用户点击了确认上传
                    try {
                      uni.showLoading({ title: '上传中...' });
                      const uploadRes = await new Promise((resolve, reject) => {
                        uni.uploadFile({
                          url: 'https://api.combinecalculate.cn/api/upload/image', // 替换成你的服务器上传接口
                          filePath: tempFilePath,
                          name: 'file',
                          success: (res) => {
                            console.log('上传成功，返回的数据：', res.data);
                            try {
                              const data = JSON.parse(res.data);
                              resolve(data);
                            } catch (error) {
                              reject('无法解析 JSON 响应');
                            }
                          },
                          fail: reject
                        });
                      });

                      const url = (uploadRes as { url: string }).url;
                      console.log('最终上传成功的图片URL:', url);

                      uni.showToast({ title: '上传成功', icon: 'success' });

                      // 这里可以把 url 存到头像地址变量上
                      // avatarUrl.value = url;
                      selectedImage.value = url; // 更新头像
                      apiChangeUser({ avatar: selectedImage.value }, uid)
                      // 这里可以进行头像的更新操作，比如调用 API 更新用户信息



                    } catch (error) {
                      console.error('上传失败:', error);
                      uni.showToast({ title: '上传失败', icon: 'none' });
                    } finally {
                      uni.hideLoading();
                    }
                  }
                }
              });
            }
          });
        }
      });
    },
    fail: (err) => {
      console.error('选择操作失败:', err);
    }
  });
};
const toDeepSeek = () => {
  //跳转页面
  uni.navigateTo({ url: "/pages/My/deepseek" })
};
onLoad(() => {

})
onShow(() => {
  getUser();
  getRemind();
  getRecord();
})
</script>

<template>
  <div class="app-container">
    <header class="header">
      <!-- <h1>uni-app</h1> -->
    </header>
    <section class="user-info">
      <!-- 显示头像，点击更换头像 -->
      <view class="avatar" @click="changeAvatar">
        <image :src="selectedImage" class="avatar-image" mode="aspectFill" />
      </view>

      <div class="user-details">
        <text class="user-name">{{ userInfo.username }}</text><text class="menu-subtitle" @click="changeName">点击修改
          ></text>
        <p class="user-id">ID:{{ uidString }}</p>
      </div>
    </section>
    <section class="menu">
      <div class="menu-item">
        <div class="menu-icon"><uni-icons type="mail-open-filled" color="#07C160" size="30"></uni-icons></div>
        <div class="menu-content">
          <div class="menu-header">
            <p class="menu-title">我的邮箱</p>

          </div>
          <div class="reminders">
            <p>{{ userInfo.email ? userInfo.email : "未设置邮箱" }}</p>
            <p class="menu-subtitle" @click="changeMail">点击修改 ></p>
          </div>
        </div>
        <div class="menu-icon"><uni-icons type="phone-filled" color="#07C160" size="30"></uni-icons></div>
        <div class="menu-content">
          <div class="menu-header">
            <p class="menu-title">我的手机</p>

          </div>
          <div class="reminders">
            <p>{{ userInfo.phone ? userInfo.phone : "未设置手机号" }}</p>
            <p class="menu-subtitle" @click="changePhone">点击修改 ></p>
          </div>
        </div>
      </div>
      <div class="menu-item">
        <div class="menu-icon"><uni-icons type="notification-filled" color="#07C160" size="30"></uni-icons></div>
        <div class="menu-content">
          <div class="menu-header">
            <p class="menu-title">我的提醒</p>
            <p class="menu-subtitle" @click="getMoreRemind">{{ remindCount }}条 ></p>
          </div>
          <div class="reminders">
            <p>{{ remindList[0].time }} {{ remindList[0].block }}:{{ remindList[0].content }}</p>

            <p v-if="remindList[1] ? true : false">{{ remindList[1].time }} {{ remindList[1].block }}:{{
              remindList[1].content }}</p>
          </div>
        </div>
      </div>
      <div class="menu-item">
        <div class="menu-icon"><uni-icons type="calendar-filled" color="#07C160" size="30"></uni-icons></div>
        <div class="menu-content">
          <div class="menu-header">
            <p class="menu-title">我的记录</p>
            <p class="menu-subtitle" @click="getMoreRecord">{{ recordCount }}条 ></p>
          </div>
        </div>
      </div>
      <div class="menu-item">
        <div class="menu-icon"><uni-icons type="chat-filled" color="#07C160" size="30"></uni-icons></div>
      <div class="menu-content">
          <div class="menu-header">
            <p class="menu-title">DeepSeek</p>
          </div>
          <div class="reminders">
            <p class="menu-subtitle" @click="toDeepSeek">立即使用DeepSeek寻求答案</p>
          </div>
        </div>
      </div>

      <div class="menu-item">
        <div class="menu-icon"><uni-icons type="info-filled" color="#07C160" size="30"></uni-icons></div>
        <div class="menu-content">
          <p class="menu-title">意见反馈</p>
        </div>
      </div>
    </section>
  </div>
</template>

<style scoped>
.app-container {
  width: 700rpx;
  margin: 0 auto;
  height: 1200rpx;
  background-color: #f5f5f5;
  border-radius: 12px;
  padding: 25rpx;
  font-family: Arial, sans-serif;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header {
  text-align: center;
  margin-bottom: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 12px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 16px;
}

.avatar image {
  width: 48px;
  height: 48px;
  background-color: #ccc;
  border-radius: 50%;
  margin-right: 12px;
}

.overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.6);
  z-index: 999;
}

.cropped-image {
  width: 200px;
  height: 200px;
  margin-top: 20px;
  object-fit: cover;
}

.user-details {
  flex-grow: 1;
}

.user-name {
  font-size: 16px;
  font-weight: bold;
  margin: 0;
}

.user-id {
  font-size: 14px;
  color: #999;
  margin: 0;
}

.menu {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.menu-item {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 12px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.menu-icon {
  font-size: 24px;
  margin-right: 12px;
}

.menu-content {
  flex-grow: 1;
}

.menu-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.menu-title {
  font-size: 16px;
  font-weight: bold;
  margin: 0;
}

.menu-subtitle {
  top: 50rpx;
  font-size: 14px;
  color: #999;
  margin: 0;
}

.reminders {
  margin-top: 8px;
  font-size: 14px;
  color: #666;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 80%;
}
</style>